---
title: FPDF_LoadMemDocument
description: Load a PDF document from memory
searchable: true
---

# FPDF_LoadMemDocument

`FPDF_LoadMemDocument(data_buf, size, password)`

## Description

Loads a PDF document from memory. This function is one of the primary ways to open a PDF document when you have the PDF data available in memory (e.g., after downloading a PDF file using `fetch`).

## Prerequisites

This example uses the `initializePdfium` helper function from our [Getting Started](/docs/pdfium/getting-started#initializing-pdfium) guide. Make sure to include this function in your code before trying the examples below.

## Parameters

| Name | Type | Description |
|------|------|-------------|
| data_buf | number | Pointer to a memory buffer containing the PDF data. Must be allocated using `pdfium.pdfium.wasmExports.malloc()`. |
| size | number | Size of the PDF data in bytes. |
| password | number | Pointer to a null-terminated UTF-8 string containing the password for encrypted documents, or 0 for no password. |

## Return Value

Returns a document handle (a number) on success, or 0 on failure. When a failure occurs, you can call `FPDF_GetLastError()` to retrieve an error code that provides more information about what went wrong.

## Error Codes

| Code | Meaning |
|------|---------|
| 0 | Success (no error) |
| 1 | Unknown error |
| 2 | File not found or could not be opened |
| 3 | File not in PDF format or corrupted |
| 4 | Password required or incorrect password |
| 5 | Unsupported security scheme |
| 6 | Page not found or content error |

## Example

```typescript
// Note: The initializePdfium function is a helper that initializes the PDFium library.
// For the full implementation, see: /docs/pdfium/getting-started
import { init, WrappedPdfiumModule } from '@embedpdf/pdfium';

// Create a singleton for PDFium instance
let pdfiumInstance: WrappedPdfiumModule | null = null;

async function initializePdfium() {
  if (pdfiumInstance) return pdfiumInstance;
  
  const response = await fetch('https://cdn.jsdelivr.net/npm/@embedpdf/pdfium/dist/pdfium.wasm');
  const wasmBinary = await response.arrayBuffer();
  pdfiumInstance = await init({ wasmBinary });
  
  // Initialize the PDFium extension library
  pdfiumInstance.PDFiumExt_Init();
  
  return pdfiumInstance;
}

async function loadPdfFromMemory(pdfData: Uint8Array) {
  // Initialize PDFium WASM module (will reuse existing instance if available)
  const pdfium = await initializePdfium();
  
  // Allocate memory for the PDF data
  const filePtr = pdfium.pdfium.wasmExports.malloc(pdfData.length);
  
  // Copy the PDF data to the allocated memory
  pdfium.pdfium.HEAPU8.set(pdfData, filePtr);
  
  // For password-protected PDFs, set up a password
  // For unprotected PDFs, you can pass 0 for the password
  // const passwordPtr = pdfium.pdfium.wasmExports.malloc(passwordString.length + 1);
  // pdfium.pdfium.stringToUTF8(passwordString, passwordPtr, passwordString.length + 1);
  
  // Load the PDF document
  const docPtr = pdfium.FPDF_LoadMemDocument(filePtr, pdfData.length, 0);
  
  if (!docPtr) {
    // Get the error code
    const error = pdfium.FPDF_GetLastError();
    
    // Map error code to message
    let errorMessage = 'Unknown error';
    switch (error) {
      case 1: errorMessage = 'Unknown error'; break;
      case 2: errorMessage = 'File not found or could not be opened'; break;
      case 3: errorMessage = 'File not in PDF format or corrupted'; break;
      case 4: errorMessage = 'Password required or incorrect password'; break;
      case 5: errorMessage = 'Unsupported security scheme'; break;
      case 6: errorMessage = 'Page not found or content error'; break;
    }
    
    // Clean up allocated memory
    pdfium.pdfium.wasmExports.free(filePtr);
    // pdfium.pdfium.wasmExports.free(passwordPtr); // If using a password
    
    throw new Error(`Failed to load PDF: ${errorMessage} (code ${error})`);
  }
  
  // Free the memory used for the PDF data since it's been loaded into the document
  pdfium.pdfium.wasmExports.free(filePtr);
  // pdfium.pdfium.wasmExports.free(passwordPtr); // If using a password
  
  return { pdfium, docPtr };
}

// Usage example
async function exampleUsage() {
  try {
    // Fetch a PDF file
    const response = await fetch('sample.pdf');
    const buffer = await response.arrayBuffer();
    const pdfData = new Uint8Array(buffer);
    
    // Load the PDF document
    const { pdfium, docPtr } = await loadPdfFromMemory(pdfData);
    
    // Now you can use the document for various operations
    // For example, get the page count
    const pageCount = pdfium.FPDF_GetPageCount(docPtr);
    console.log(`PDF loaded successfully with ${pageCount} pages`);
    
    // Perform other operations with the document...
    
    // When done, close the document to free resources
    pdfium.FPDF_CloseDocument(docPtr);
  } catch (error) {
    console.error('Error handling PDF:', error);
  }
}

exampleUsage();
```

## Notes

- Always free the memory allocated for `data_buf` using `pdfium.pdfium.wasmExports.free()` when you're done with it, even if `FPDF_LoadMemDocument` fails.
- Similarly, if you allocated memory for a password string, make sure to free that memory as well.
- When you're done with the document, call `FPDF_CloseDocument(docPtr)` to release the document's resources.
- This function is commonly used in web applications to load PDFs that have been downloaded using `fetch` or uploaded by the user.
- For very large documents, consider using `FPDF_LoadCustomDocument` instead, which allows for on-demand loading of PDF data.

## Related Functions

- [FPDF_CloseDocument](/docs/pdfium/functions/FPDF_CloseDocument) - Close a loaded PDF document
- [FPDF_GetLastError](/docs/pdfium/functions/FPDF_GetLastError) - Get the error code for the last failed operation